
public class BubbleSort {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int[] a = {5, 2, 7, 1, 8, 16, 4};
		int[] sortedArray = sortArrayByBubble(a);
		int[] b = {5, 2, 7, 1, 8, 16, 4};
		int[] sortedArrayPeter = sortArrayPeterBubbleStyle(b);

		for (int i = 0; i < sortedArray.length; i++) {
			System.out.print("Classic Bubble sort: ");
			System.out.println(sortedArray[i]);
		}
		for (int i = 0; i < sortedArrayPeter.length; i++) {
			System.out.print("Peter's Classic Bubble sort: ");
			System.out.println(sortedArrayPeter[i]);
		}
	}
	
	private static int[] sortArrayPeterBubbleStyle (int[] a) {
		int temp = 0;
		for (int i = 0; i < a.length; i++) {
			for (int j = 0; j < a.length - 1; j++) {
				if (a[j] > a[j+1]) {
					temp = a[j];
					a[j] = a[j+1];
					a[j+1] = temp;
				}
			}
		}
		return a;
	}
	
	private static int[] sortArrayByBubble(int[] a) {
		int newLowest = 0;              // index of first comparison
	    int newHighest = a.length - 1;  // index of last comparison
	  
	    while (newLowest < newHighest) {
	        int highest = newHighest;
	        int lowest  = newLowest;
	        newLowest = a.length;    // start higher than any legal index
	        for (int i = lowest; i < highest; i++) {
	            if (a[i] > a[i+1]) {
	               // exchange elements
	               int temp = a[i];
	               a[i] = a[i+1];
	               a[i+1] = temp;
	               if (i < newLowest) {
	                   newLowest = i-1;
	                   if (newLowest < 0) {
	                       newLowest = 0;
	                   }
	               } else if (i > newHighest) {
	                   newHighest = i + 1;
	               }
	            }
	        }
	    }
	    return a;
	}

}
